#!/usr/bin/env python
#!-*- coding:utf-8 -*-
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google.appengine.ext import db

import os
import cgi

import models
import myutils

class UserInfo():
    userid = ""
    passwd = ""
    kaishi = ""
    syuryo = ""
    jitudo = ""
    zan_futu = ""
    zan_sinya = ""
    zan_gokei = ""
    shimebi = 0
    register =  True
    register_hash = ""

# ユーザ登録
class RegistrationHandler(webapp.RequestHandler):
    """
    ユーザ登録
    """
    def get(self):
        us = myutils.Get_UserSession(self.request.cookies)
        if not us:
            # UserSessionなし
            ui = UserInfo()
            ui.userid = ""
            ui.passwd = ""
            ui.kaishi = ""
            ui.syuryo = ""
            ui.jitudo = ""
            ui.zan_futu = ""
            ui.zan_sinya = ""
            ui.zan_gokei = ""
            ui.shimebi = ""
            ui.register =  True
            ui.register_hash = ""
        else:
            # UserSessionあり
            ui = db.GqlQuery("SELECT * FROM UserInfo Where userid = :1", us.userid).get()
        
        simebi_html = ""
        for ii in (range(1,32)):
            selected = ""
            if not ui.shimebi == "":
                if int(ui.shimebi) == ii: selected = "selected"
            simebi_html += """<option value="%d" %s>%d</option>""" % (ii, selected, ii)
        
        template_values = {'userinfo': ui,
                           'simebi': simebi_html}
        
        path = os.path.join(os.path.dirname(__file__), 'templates/registration.html')
        self.response.out.write(template.render(path, template_values))

    def post(self):
        us = myutils.Get_UserSession(self.request.cookies)       
        
        userid_str = cgi.escape(self.request.get('userid'))
        passwd_str = cgi.escape(self.request.get('passwd'))
        repasswd_str = cgi.escape(self.request.get('repasswd'))
        kaishi_str = cgi.escape(self.request.get('kaishi'))
        syuryo_str = cgi.escape(self.request.get('syuryo'))
        jitudo_str = cgi.escape(self.request.get('jitudo'))
        zan_futu_str = cgi.escape(self.request.get('zan_futu'))
        zan_sinya_str = cgi.escape(self.request.get('zan_sinya'))
        zan_gokei_str = cgi.escape(self.request.get('zan_gokei'))
        simebi_str = cgi.escape(self.request.get('simebi'))

        userinfo = db.GqlQuery("SELECT * FROM UserInfo Where userid = :1", userid_str)
        if userinfo.count() > 0 and not us:
            # UserSessionなし
            ui = UserInfo()
            ui.userid = userid_str
            ui.passwd = passwd_str
            ui.kaishi = kaishi_str
            ui.syuryo = syuryo_str
            ui.jitudo = jitudo_str
            ui.zan_futu = zan_futu_str
            ui.zan_sinya = zan_sinya_str
            ui.zan_gokei = zan_gokei_str
            ui.shimebi = simebi_str
            ui.register =  True
            ui.register_hash = ""

            simebi_html = ""
            for ii in (range(1,32)):
                selected = ""
                if not ui.shimebi == "":
                    if int(ui.shimebi) == ii: selected = "selected"
                simebi_html += """<option value="%d" %s>%d</option>""" % (ii, selected, ii)
                        
            template_values = {'errmsg': u"入力したメールアドレスは登録済みです。",
                               'userinfo': ui,
                               'simebi': simebi_html}
        
            path = os.path.join(os.path.dirname(__file__), 'templates/registration.html')
            self.response.out.write(template.render(path, template_values))

        else:
            for u in userinfo: u.delete()
            ui = models.UserInfo(userid = userid_str, passwd = passwd_str)
            ui.userid = userid_str
            ui.passwd = passwd_str
            ui.kaishi = kaishi_str
            ui.syuryo = syuryo_str
            ui.jitudo = jitudo_str
            ui.zan_futu = zan_futu_str
            ui.zan_sinya = zan_sinya_str
            ui.zan_gokei = zan_gokei_str
            ui.shimebi = int(simebi_str)
            ui.register =  True
            ui.register_hash = ""
    
            ui.put()

            if not us: template_values = {'crud': u"登録"}
            else: template_values = {'crud': u"更新"}
            
            path = os.path.join(os.path.dirname(__file__), 'templates/mess_usercommit.html')
            self.response.out.write(template.render(path, template_values))

# ログイン
class LoginHandler(webapp.RequestHandler):
    """
    ログイン
    """
    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'templates/login.html')
        self.response.out.write(template.render(path,{}))

    def post(self):
        userid_str = cgi.escape(self.request.get('userid'))
        passwd_str = cgi.escape(self.request.get('passwd'))

        userinfo = db.GqlQuery("SELECT * FROM UserInfo Where userid = :1 and passwd = :2", userid_str, passwd_str)
        if userinfo.count() > 0:
            # セッションの作成
            myutils.Create_UserSession(self.request, self.response, userid_str)
        
        return self.redirect("/")

def main():
    application = webapp.WSGIApplication([('/Registration', RegistrationHandler),                                          
                                          ('/Login', LoginHandler)],
                                         debug=True)
    util.run_wsgi_app(application)

if __name__ == "__main__":
  main()